<template>
	<view class="work-container">
		<u--form labelPosition="left" style="margin-right: 2%;margin-left: 2%;">
			<u-form-item label="请选择分类" labelWidth="12vh" @click="showCategorySelect">
				<u--input v-model="selectCategoryName" style="text-align: center !important;" disabled disabledColor="#ffffff" placeholder="请选择分类"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="请选择社区" labelWidth="12vh" @click="showCommunitySelect">
				<u--input v-model="selectCommunityName" style="text-align: center !important;"  disabled disabledColor="#ffffff" placeholder="请选择社区"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="名称" labelWidth="12vh">
				<u--input v-model="form.name"></u--input>
			</u-form-item>
			<u-form-item label="简介" labelWidth="12vh">
				<u--textarea placeholder="请描述下详细信息" count maxlength="1000" v-model="form.content"
					style="height: 50vh;"></u--textarea>
			</u-form-item>
			<u-form-item label="商品图片" labelWidth="12vh">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :auto-upload="false"
					:maxCount="10"></u-upload>
			</u-form-item>
			<u-form-item label="微信" labelWidth="12vh">
				<u--input v-model="form.weixin"></u--input>
			</u-form-item>
			<u-form-item label="QQ" labelWidth="12vh">
				<u--input v-model="form.qq"></u--input>
			</u-form-item>
			<u-form-item label="联系方式" labelWidth="12vh">
				<u--input v-model="form.phone"></u--input>
			</u-form-item>

			<view style="margin-top:-8vh">
				<u-button type="primary" text="提交" customStyle="margin-top: 50px" @click="submit"></u-button>
				<u-button type="error" text="重置" customStyle="margin-top: 10px" @click="reset"></u-button>
			</view>

		</u--form>
		<u-toast ref="uToast"></u-toast>
		<u-action-sheet :show="showCategory" :actions="categorys" title="请选择分类" description="如果选择保密会报错"
			@close="showCategory = false" @select="categorySelect">
		</u-action-sheet>
		<u-action-sheet :show="showCommunity" :actions="communitys" title="请选择社区" description="如果选择保密会报错"
			@close="showCommunity = false" @select="communitySelect">
		</u-action-sheet>
	</view>
</template>

<script>
	import {
		getInfos,
		addInfo
	} from "@/api/info/info"
	import {
		getCategory
	} from "@/api/category/category"
	import {
		getCommunity
	} from "@/api/commmunity/index"
	import {
		uploadFile
	} from "@/api/system/oss";
import { getToken } from '@/utils/auth'
import config from '@/config'
	export default {
		data() {
			return {
				fileList1: [],
				form: {},
				categorys: [],
				communitys:[],
				showCategory: false,
				showCommunity: false,
				selectCategoryName:'',
				selectCommunityName:''
			}
		},
		onLoad(options) {

		},
		methods: {
			showCategorySelect() {
				this.showCategory = true;
				this.getCategorys();
				this.hideKeyboard()
			},
			categorySelect(e) {
				this.form.type=e.categoryId
				this.selectCategoryName=e.name
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			showCommunitySelect() {
				this.showCommunity = true;
				this.getCommunitys();
				this.hideKeyboard()
			},
			communitySelect(e) {
				this.form.communityId=e.communityId
				this.selectCommunityName=e.communityName
			},
			getCommunitys() {
				getCommunity().then(res => {
					console.info(res,123)
					const modifiedCommunity = res.rows.map(community => {
					      return {
					        ...community, 
					        name: community.communityName, 
					      };
					    });
					    this.communitys = modifiedCommunity; 
				})
			},
			getCategorys() {
				getCategory().then(res => {
					const modifiedCategories = res.rows.map(category => {
					      return {
					        ...category, 
					        name: category.categoryName, 
					      };
					    });
					    this.categorys = modifiedCategories; 
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(file) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url:config.baseUrl+'/resource/oss/upload',
						filePath:file,
						name:'file',
						header:{
							"Authorization":"Bearer "+getToken(),
							"clientId" : "428a8310cd442757ae699df5d894f051"
						},
						success:(res)=>{
							console.info(JSON.parse(res.data).data.url)
							resolve(JSON.parse(res.data).data.url)
						}
					})
					
					
					
					// uploadFile({
					// 	filePath: file
					// }).then(res => {
					// 	if (res.code === 200) {
					// 		resolve(res.data.url);
					// 	} else {
					// 		reject(new Error('上传失败'));
					// 	}
					// }).catch(error => {
					// 	reject(error);
					// });
				});
			},
			submit() {
				this.form.photos = this.fileList1.map(file => file.url).join(",")
				addInfo(this.form).then(res => {
					if (res.code === 200) {
						this.$refs.uToast.show({
							type: 'success',
							message: '添加成功',
							iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png',
							duration: 3000
						})
						this.$tab.switchTab(`/pages/mine/index`)
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	/* #ifndef APP-NVUE */
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #fff;
		min-height: 100%;
		height: auto;
	}

	view {
		font-size: 14px;
		line-height: inherit;
	}

	/* #endif */
</style>